class NoteHistoryTracker {
    private storageKey = 'viewedNoteIds';
    private cache: Set<string> | null = null;
  
    // 从localStorage加载数据到缓存
    private loadCache(): Set<string> {
      if (this.cache !== null) return this.cache;
      
      try {
        const storedValue = localStorage.getItem(this.storageKey);
        const ids = storedValue ? JSON.parse(storedValue) : [];
        this.cache = new Set(ids);
        return this.cache;
      } catch (error) {
        console.error('Failed to load note history:', error);
        this.cache = new Set();
        return this.cache;
      }
    }
  
    // 保存缓存到localStorage
    private saveCache(): void {
      try {
        if (this.cache === null) return;
        const idsArray = Array.from(this.cache);
        localStorage.setItem(this.storageKey, JSON.stringify(idsArray));
      } catch (error) {
        console.error('Failed to save note history:', error);
      }
    }
  
    // 添加浏览过的note id
    public addNoteId(noteId: string): void {
      const cache = this.loadCache();
      
      // 如果已存在则删除旧记录
      if (cache.has(noteId)) {
        cache.delete(noteId);
      }
      
      // 添加到最前面（Set按添加顺序排序）
      cache.add(noteId);
      this.saveCache();
    }
  
    // 获取所有浏览过的note ids（按最近浏览排序）
    public getAllNoteIds(): string[] {
      const cache = this.loadCache();
      // 反转以获得最近浏览到最早浏览的顺序
      return Array.from(cache).reverse();
    }
  
    // 清除缓存
    public clearCache(): void {
      this.cache = null;
    }
  
    // 检查note是否已浏览
    public hasNoteId(noteId: string): boolean {
      return this.loadCache().has(noteId);
    }
  
    // 获取浏览历史长度
    public getSize(): number {
      return this.loadCache().size;
    }

    public clearHistory() {
        localStorage.setItem(this.storageKey, "");
        this.cache = null;
    }
  }
  
  export const noteHistoryTracker = new NoteHistoryTracker();  